<!--
* description: 采购单制作-新增编辑
-->
<template>
  <section class="editCarBrand">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      @close="sendCode"
      width="1000px"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :styleType="$store.state.app.dialogType"
      ></dialogHeader>
      <div class="filter-container filter-params">
        <el-row :gutter="26">
          <component
            v-for="comp in tableComponents.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :validrule="comp.validrule"
            :key="comp.compKey"
            :codeField="comp.codeField"
            :textField="comp.textField"
            :popupsKey="comp.compKey"
            :is="comp.component"
            :code="formField[comp.codeField]"
            :text="formField[comp.textField]"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
            :disabled="comp.disabled"
            :isRequire="comp.isRequire"
            :span="comp.span || 8"
            :isMul="comp.isMul"
            :labelName="comp.labelName"
            :readonly="comp.readonly"
            :showPlaceholder="comp.showPlaceholder"
            :dateOptionsType="comp.dateOptionsType"
            :options="comp.options"
            :dynamicIsShowSelect="true"
            :dynamicIsColumnDrop="true"
          ></component>
        </el-row>
        <el-row :gutter="34" style="margin-bottom: 5px">
          <el-col :span="24">
            <div class="dialogTitle">
              <span class="dialogTitleButton">
                <span class="dialogTip">选择供应商会清空表格的明细数据</span>
                <el-button
                  class="iconfont icon-newlyAdded"
                  @click="tableDataAdd"
                  >新增明细</el-button
                >
              </span>
            </div>
            <span>
              <el-button class="strlke" @click="tableDataDel">删除</el-button>
            </span>
          </el-col>
        </el-row>
      </div>
       <!-- 表格-->
            <el-table
              ref="table"
              :data="tableData"
              style="width: 100%"
              height="300"
              border
              v-loading="listLoading"
            >
              <el-table-column align="center" type="selection" width="55" />
              <el-table-column label="序号" width="60" align="center">
                <template slot-scope="scope">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox label="复选框 A"></el-checkbox>
                  </el-checkbox-group>
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-link
                    type="primary"
                    class="el-icon-delete"
                    :underline="false"
                    @click="tableDataDel(scope.$index)"
                    title="删除"
                    style="font-size: 12px"
                    >删除</el-link
                  >
                </template>
              </el-table-column> -->
              <el-table-column
                label="备件编号"
                width="150"
                align="center"
                prop="PART_NO"
              ></el-table-column>
              <el-table-column
                label="备件名称"
                prop="PART_NAME"
                width="120"
                align="center"
              ></el-table-column>
              <el-table-column
                label="标准价格"
                prop="PURCHASE_PRICE"
                width="120"
                align="center"
              ></el-table-column>
              <el-table-column label="采购数量+" width="120" align="center">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.PURCHASE_QTY"
                    type="text"
                    @input="numChange(scope)"
                    style="width: 100%"
                    class="tableTemplate"
                  ></el-input>
                </template>
              </el-table-column>
              <!-- 要求到货时间 -->
              <el-table-column label="要求到货时间" width="100%" align="center">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.RA_TIME"
                    :picker-options="pickerOptions0"
                    type="date"
                    placeholder="选择日期"
                    class="isRequire: true"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <!-- 要求到货时间 -->

              <el-table-column
                label="采购SNP"
                prop="SNP_IN"
                width="120"
                align="center"
              />
              <el-table-column
                label="销售SNP"
                prop="SNP_OUT"
                width="120"
                align="center"
              />
              <!-- <el-table-column label="调拨SNP" prop="SNP_MOVE" width="120" align="center" /> -->
              <el-table-column
                label="当前库存"
                prop="DQ_QTY"
                width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <div class="cell">{{ scope.row.DQ_QTY }}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="安全库存"
                prop="AQ_QTY"
                width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <div class="cell">{{ scope.row.AQ_QTY }}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="预入库数量"
                prop="INBOUND_QTY"
                width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <div class="cell">{{ scope.row.INBOUND_QTY }}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="预出库数量"
                prop="OUTBOUND_QTY"
                width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <div class="cell">{{ scope.row.OUTBOUND_QTY }}</div>
                </template>
              </el-table-column>
            </el-table>
        <!-- 表格 -->
      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          @click="comp.clickEvent"
          >{{ comp.text }}</el-button
        >
      </div>
      <editPartNoTable
        v-if="isEditShow"
        @detailPartNoClose="detailPartNoClose"
        @confirmPartNo="confirmPartNo"
        :isEditShow="isEditShow"
        :editformField="formField"
        :editTableData="tableData"
      />
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from "@/components/wms/mixins/formMixins";
import { wmsApis } from "@/api/wms/purchase/api";
import storage from "@/utils/storage";
import request from "@/utils/request";
import { message } from 'ant-design-vue';
export default {
  // 组件混入对象
  mixins: [formMixins],
  components: {
    dialogHeader: () => import("@/components/dialogHeader"), //弹窗标题
    editPartNoTable: () => import("./editPartNoTable"),
  },
  watch: {
    popupsVisible(val) {
      if (val) {
        if (
          this.formField.pageId !== "" &&
          this.$route.query.pageId !== undefined &&
          this.$route.query.pageId !== this.formField.pageId
        ) {
          this.formField.pageId = this.$route.query.pageId;
          this.formField.pageName = this.$route.query.pageName;
        }
        this.formField.langLabelName = this.formField.label;
        this.backFormField = JSON.parse(JSON.stringify(this.formField));
      }
    },
  },
  data() {
    return {
      //
      // yDate:'',
      // 日期不能选择今天之前的
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      // 日期不能选择今天之前的
      pickerOptions: {
        // 计费日期的约束条件
        disabledDate: this.disabledDate,
      },

      // 保存API配置对象
      apiConfig: wmsApis.savePurchase,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          clickEvent: () => this.save(),
          text: "保存", //"保存"
        },
        {
          compKey: "btnKey2",
          type: "",
          size: "small",
          clickEvent: () => this.close("1"),
          text: "关闭", //"关闭"
        },
      ],
      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: "edit_compKey1",
          labelName: "采购单号",
          codeField: "PURCHASE_CODE",
          component: () => import("@/components/wms/commonInput"),
          type: "inputText",
          isMust: true,
          disabled: true,
          span: 8,
          showPlaceholder: "",
        },
        {
          compKey: "edit_compKey2",
          labelName: "供应商",
          textField: "PARTNER_SHORT_NAME",
          codeField: "SUPPLIER_CODE",
          component: () =>
            import("@/components/wms/wmsEjectWindows/wmsSupplier"),
          type: "propus",
          isMust: true,
          span: 8,
          isMul: false,
          isRequire: true,
          readonly: false,
          returnCodeField: "SUPPLIER_CODE",
          returnTextField: "PARTNER_SHORT_NAME",
          disabled: !this.isAdd(),
          changed: () => {
            this.tableData = [];
          },
        },
        {
          compKey: "edit_compKey3",
          labelName: "采购类型",
          codeField: "PURCHASE_TYPE",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          isMul: false,
          span: 8,
          options: [],
          isRequire: true,
          disabled: !this.isAdd(),
        },
        {
          compKey: "edit_compKey4",
          labelName: "到货仓库",
          codeField: "WAREHOUSE_ID",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          isMul: false,
          span: 8,
          options: [],
          isRequire: true,
          disabled: !this.isAdd(),
          changed: (val) => {
            if (!val) {
              return;
            }
            if (this.tableData.length == 0) {
              return;
            }
            let partNoArr = [];
            this.tableData.forEach((item) => {
              partNoArr.push(item.PART_NO);
              item.DQ_QTY = 0;
              item.AQ_QTY = 0;
              item.INBOUND_QTY = 0;
              item.OUTBOUND_QTY = 0;
            });
            request({
              url: "/mp/wm/vl/warehouse/purchase/queryPartNoStorage.do",
              method: "post",
              data: {
                WAREHOUSE_ID: val,
                PART_NOS: partNoArr.join(","),
              },
            }).then((res) => {
              if (res.listRow && res.listRow.length > 0) {
                res.listRow.forEach((item) => {
                  this.tableData.forEach((checkItem) => {
                    if (item.PART_NO == checkItem.PART_NO) {
                      checkItem.DQ_QTY = item.DQ_QTY;
                      checkItem.AQ_QTY = item.AQ_QTY;
                      checkItem.INBOUND_QTY = item.INBOUND_QTY;
                      checkItem.OUTBOUND_QTY = item.OUTBOUND_QTY;
                    }
                  });
                });
              }
              let talbeArr = this.tableData;
              this.tableData = [];
              this.$nextTick(() => {
                this.tableData = talbeArr;
              });
            });
          },
        },
        {
          compKey: "edit_compKey5",
          labelName: "要求到货时间",
          codeField: "RA_TIME",
          component: () => import("@/components/org/datePicker/datePicker"),
          type: "date",
          isMust: true,
          span: 8,
          isRequire: false,
          // 日期不必填
          // disabled: !this.isAdd(),
          dateOptionsType: "3",
          changed: (val) => {
            // this.yDate = val
            this.tableData.forEach((item) => {
              this.$set(item, "RA_TIME", val);
            });
            // console.log(this.tableData);
            this.$forceUpdate
          },
        },
      ],
      // 标题
      textMap: {
        add: "新增采购单",
        edit: "编辑采购单",
      },
      // 表单数据（无需赋值，由混入对象赋值）
      formField: {
        PURCHASE_CODE: "",
        SUPPLIER_CODE: "",
        PARTNER_SHORT_NAME: "",
        PURCHASE_TYPE: "",
        WAREHOUSE_ID: "",
        RA_TIME: "",
        PURCHASE_ID: "",
      },
      //表格数据
      tableData: [],
      // 表格加载字段
      listLoading: false,

      // 控制备件明细弹窗
      isEditShow: false,
    };
  },
  methods: {
    // 今天日期之前不能选择
    disabledDate(time) {
      return time.getTime() < new Date(date).getTime();
    },

    onCreated() {
      if (this.curPopupsVisible) {
        request({
          url: "/mp/wm/vl/warehouse/purchase/queryPurchaseTypeBox2.do",
          method: "post",
          data: {
            PAGE_STATUS: "1",
          },
        }).then((res) => {
          if (res.listRow && res.listRow.length > 0) {
            res.listRow.map((item) => {
              this.tableComponents[2].options.push({
                label: item.PURCHASE_TYPE_NAME,
                value: item.PURCHASE_TYPE,
              });
            });
          }
        });

        request({
          url: "/mp/wm/vl/basedata/warehouseuser/queryUserByWHBox.do",
          method: "post",
          data: {
            IS_ENABLE: "1",
          },
        }).then((res) => {
          res.listRow.map((item) => {
            this.tableComponents[3].options.push({
              label: item.WAREHOUSE_NAME,
              value: item.WAREHOUSE_ID,
            });
          });
        });

        if (this.popupsState === "edit") {
          this.listLoading = true;
          request({
            url: "/mp/wm/vl/warehouse/purchase/queryPurchaseD.do",
            method: "post",
            data: {
              pageIndex: 1,
              pageSize: 999,
              PURCHASE_CODE: this.formField.PURCHASE_CODE,
            },
          })
            .then((res) => {
              this.listLoading = false;
              if (res.result === "1") {
                if (res.listResult) {
                  this.tableData = res.listResult.rows;
                }
              } else {
                if (res.msg || res.debugMsg) {
                  this.$message({
                    message: res.debugMsg ? res.debugMsg : res.msg,
                    uration: 2000,
                  });
                }
              }
            })
            .catch((err) => {
              console.info(err);
              this.listLoading = false;
            });
        }
      }
    },
    confirmPartNo(checkList) {
      this.isEditShow = false;
      checkList.forEach((item) => {
        // item.RA_TIME = this.yDate
        this.tableData.push(item);
      });
    },
    // 采购数量change事件
    numChange(scope) {
      if (scope.row.PURCHASE_QTY < 1) {
        scope.row.PURCHASE_QTY = "";
      }
      scope.row.PURCHASE_QTY = (scope.row.PURCHASE_QTY + "").replace(
        /[^\d]/g,
        ""
      );
    },
    // 新增按钮 点击事件
    tableDataAdd() {
      if (!this.formField.SUPPLIER_CODE) {
        this.$message({
          message: "请选择供应商",
        });
        return;
      }
      if (!this.formField.WAREHOUSE_ID) {
        this.$message({
          message: "请选择仓库",
        });
        return;
      }
      this.isEditShow = true;
    },
    detailPartNoClose() {
      this.isEditShow = false;
    },
    //  删除按钮 点击事件
    tableDataDel() {
      // 批量删除
      const seletedDatas = this.$refs.table.selection
      if (seletedDatas.length === 0) {
           this.$message({
          message: "请至少选择一条数据",
        });
        return
      }
      this.$confirm("您确定是否要进行此操作？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
      })
        .then(() => {
          // 批量删除
          const arr = []
          this.tableData.forEach(item => {
            const filterData = seletedDatas.filter(element => element.PART_NO === item.PART_NO)
            if (filterData.length === 0) {
              arr.push(item)
            }
          });
          this.tableData = arr
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    //保存
    save() {
      let flag = false;
      if (this.tableData.length < 1) {
        this.$message({
          message: "至少保存一条采购明细",
        });
        return;
      }
      this.tableData.forEach((item) => {
        if (!item.PURCHASE_QTY || !item.RA_TIME) {
          flag = true;
        }
      });
      if (flag) {
        this.$message({
          message: "明细中的采购数量未输入或者要求到货日期未选择",
        });
        return;
      }

      this.$utils.validataMoth(this, "validpopup");
      if (this.valid) {
        var saveObj = JSON.parse(JSON.stringify(this.formField));
        saveObj.PurchaseD = this.tableData;
        //保存表单
        this.saveForm(saveObj);
        storage.remove(this.$route.query.pageCode);
      }
    },
  },
};
</script>
<style type="text/css" lang="scss" scoped>
.dialogTitle {
  text-align: left;
  overflow: hidden;
}
.dialogTitleButton {
  float: right;
}
/deep/ .tableTemplate .el-input__inner {
  border: none;
}
.dialogTip {
  color: red;
  margin-right: 10px;
  font-size: 12px;
}
.strlke {
}
.el-table .el-date-editor {
  width: 100%;
}
</style>
